import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import * as noteApi from '@/api/note/note';
import { Note } from '@/types/note/note';
import { ElMessage } from 'element-plus';
// import { SignUtil } from '@/util/signin';

export interface TempNote {
    id: string;
    title: string;
    content: string;
    lastModified: Date | null;
    tags?: string[];
}

export interface NoteTemplate {
    id: string;
    name: string;
    title: string;
    content: string;
}

export const useNoteStore = defineStore('note', () => {
    // State
    //const tempnotes = ref<TempNote[]>([]);
    const notes = ref<Note[]>([]);
    const searchQuery = ref('');
    const templates = ref<Record<string, NoteTemplate>>({
        daily: {
            id: 'daily',
            name: '日记模板',
            title: '日记',
            content: `# 今日日记\n## 今日完成\n- \n\n## 今日感想\n- \n\n## 明日计划\n- \n`
        },
        study: {
            id: 'study',
            name: '学习笔记',
            title: '学习笔记',
            content: `# 学习笔记\n\n## 知识要点\n- \n\n## 重要概念\n- \n\n## 示例代码\n\`\`\`\n\n\`\`\`\n\n## 疑问和解答\n- Q: \n- A: \n\n## 复习提醒\n- [ ] 一天后复习\n- [ ] 一周后复习\n- [ ] 一月后复习`
        },
        meeting: {
            id: 'meeting',
            name: '会议记录',
            title: '会议记录',
            content: `# 会议记���\n\n## 基本信息\n- 日期：\n- 时间：\n- 地点：\n- 参会人员：\n\n## 会议议程\n1. \n2. \n\n## 讨论要点\n- \n\n## 决议事项\n- [ ] \n\n## 后续跟进\n- [ ] `
        },
        project: {
            id: 'project',
            name: '项目计划',
            title: '项目计划',
            content: `# 项目计划\n\n## 项目概述\n- 项目名称：\n- 开始时间：\n- 预计完成：\n- 负责人：\n\n## 目标\n1. \n2. \n\n## 任务分解\n- [ ] 阶段一\n  - [ ] 任务1.1\n  - [ ] 任务1.2\n\n## 风险评估\n- \n\n## 资源需求\n- `
        },
        reading: {
            id: 'reading',
            name: '读书笔记',
            title: '读书笔记',
            content: `# 读书笔记\n\n## 书籍信息\n- 书名：\n- 作者：\n- 阅读日期：\n\n## 核心观点\n- \n\n## 精彩片段\n> \n\n## 个人感悟\n- \n\n## 行动计划\n- [ ] `
        },
        problem: {
            id: 'problem',
            name: '问题解决',
            title: '问题解决记录',
            content: `# 问题解决记录\n\n## 问题描述\n- 现象：\n- 影响：\n- 紧急程度：\n\n## 原因分析\n1. \n2. \n\n## 解决方案\n- 方案A：\n  - 优点：\n  - 缺点：\n\n## 执行计划\n1. [ ] \n2. [ ] \n\n## 复盘总结\n- 经验：\n- 教训：`
        },
        idea: {
            id: 'idea',
            name: '创意记录',
            title: '创意灵感',
            content: `# 创意灵感\n\n## 灵感来源\n- \n\n## 主要构思\n- \n\n## 可行性分析\n### 优势\n- \n\n### 挑战\n- \n\n## 行动步骤\n1. [ ] \n\n## 需要资源\n- `
        },
        review: {
            id: 'review',
            name: '复习总结',
            title: '阶段性复习总结',
            content: `# 阶段性复习总结\n\n## 本周重点\n1. \n\n## 掌握情况\n- 已掌握：\n- 需加强：\n\n## 易错点总结\n1. \n\n## 解题技巧\n- \n\n## 复习计划\n- [ ] `
        }
    });
    const isLoading = ref(false);
    const error = ref<string | null>(null);

    // 获取笔记列表
    const initializeStore = async () => {
        isLoading.value = true;
        error.value = null;
        let response;
        try {
            response = await noteApi.getNotes();
            if (response.code === 200) {
                notes.value = response.data.records;
            }
        } catch (error) {
            error.value = error.message;
            ElMessage.error(error.message);
        } finally {
            isLoading.value = false;
        }
    };

    // 创建笔记
    const createNote = async () => {
        // const userId = SignUtil.getUserId();
        // if (!userId) {
        //     throw new Error('请先登录');
        // }

        const newNote = {
            userId: Number(0),
            noteTitle: '新建笔记',
            noteContent: '',
            isPublic: '0'
        };

        try {
            const response = await noteApi.createNote(newNote);
            if (response.data.code === 200 || response.data.data) {
                notes.value.unshift(response.data.data);
                return response.data.data;
            }
            throw new Error('创建笔记失败');
        } catch (error) {
            ElMessage.error(error.message);
            throw error;
        }
    };

    // 更新笔记
    const updateNote = async (noteId: number, updates: Pick<Note, 'noteTitle' | 'noteContent' | 'isPublic'>) => {
        try {
            const response = await noteApi.updateNote(noteId, updates);
            if (response.data.code === 200 || response.data.data) {
                const index = notes.value.findIndex(note => note.noteId === noteId);
                if (index !== -1) {
                    notes.value[index] = { ...notes.value[index], ...response.data };
                }
                return response.data;
            }
            throw new Error('更新笔记失败');
        } catch (error) {
            ElMessage.error(error.message);
            throw error;
        }
    };

    // 删除笔记
    const deleteNote = async (noteId: number) => {
        try {
            const response = await noteApi.deleteNote(noteId);
            if (response.data.code === 200) {
                notes.value = notes.value.filter(note => note.noteId !== noteId);
            }
        } catch (error) {
            ElMessage.error(error.message);
            throw error;
        }
    };

    // 批量删除笔记
    const batchDeleteNotes = async (ids: number[]) => {
        try {
            const response = await noteApi.batchDeleteNotes(ids);
            if (response.code === 200) {
                notes.value = notes.value.filter(note => !ids.includes(note.noteId));
            }
        } catch (error) {
            ElMessage.error(error.message);
            throw error;
        }
    };

    // 搜索笔记
    const filteredNotes = computed(() => {
        const query = searchQuery.value.toLowerCase().trim();
        if (!query) return notes.value;
        return notes.value.filter(note => 
            note.noteTitle.toLowerCase().includes(query) ||
            note.noteContent.toLowerCase().includes(query)
        );
    });

    const applyTemplate = (templateId: string) => {
        const template = templates.value[templateId];
        if (!template) {
            ElMessage.error('模板不存在');
            return null;
        }
        return {
            title: template.title,
            content: template.content
        };
    };

    return {
        notes,
        searchQuery,
        filteredNotes,
        isLoading,
        error,
        templates,
        initializeStore,
        createNote,
        updateNote,
        deleteNote,
        batchDeleteNotes,
        setSearchQuery: (query: string) => searchQuery.value = query,
        applyTemplate,
    };
}); 

export type { Note };
